package com.cold.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cold.eduservice.entity.EduChapter;
import com.cold.eduservice.entity.EduVideo;
import com.cold.eduservice.entity.chapter.ChapterVo;
import com.cold.eduservice.entity.chapter.VideiVo;
import com.cold.eduservice.mapper.EduChapterMapper;
import com.cold.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cold.eduservice.service.EduVideoService;
import com.cold.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author cold
 * @since 2021-01-28
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<EduChapter> list = list(wrapper);
        List<ChapterVo> chapterVos = new ArrayList<>();
        for (EduChapter eduChapter : list){
            ChapterVo chapterVo = new ChapterVo();
            chapterVo.setId(eduChapter.getId());
            chapterVo.setTitle(eduChapter.getTitle());
            chapterVos.add(chapterVo);
        }
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        List<EduVideo> list1 = eduVideoService.list(queryWrapper);
        for (EduVideo eduVideo : list1){
            String chapterId = eduVideo.getChapterId();
            for (ChapterVo chapterVo : chapterVos){
                if(chapterId.equals(chapterVo.getId())){
                    VideiVo videiVo = new VideiVo();
                    videiVo.setId(eduVideo.getId());
                    videiVo.setTitle(eduVideo.getTitle());
                    videiVo.setVideoSourceId(eduVideo.getVideoSourceId());
                    List<VideiVo> children = chapterVo.getChildren();
                    children.add(videiVo);
                    break;
                }
            }
        }


        return chapterVos;
    }

    @Override
    public boolean removeChapterById(String chapterId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        List<EduVideo> list = eduVideoService.list(wrapper);
        int count = eduVideoService.count(wrapper);
        if(count > 0){
            throw  new GuliException(20001,"有小节，暂时无法删除");

        }else {
            int i = baseMapper.deleteById(chapterId);
            return i>0;
        }
    }
}
